package com.diandian.util;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;


/** * 图片大小处理 * 
 * @author TDW 
 * */
public class ImageUtil {
	/**  
	 * 按宽的比例更改图片的大小
	 * @param filePath 源图片路径  
	 *  @param savePath 图片保存路径  
	 *   @param width  
	 *    @return  
	 *    @throws Exception  
	 *    */ 
	public static String getRatioWidth(String filePath,String savePath, int width)   throws Exception {
		 File f = new File(filePath);  
		 BufferedImage bi = ImageIO.read(f);  
		 double wRatio = (new Integer(width)).doubleValue() / bi.getWidth(); 
		 // 宽度的比例  
		 int height = (int) (wRatio * bi.getHeight()); 
		 // 图片转换后的高度  
		 Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH); 
		 // 设置图像的缩放大小  
		 AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(wRatio, wRatio), null); 
		 // 设置图像的缩放比例 
		 image = op.filter(bi, null);  
		 int lastLength = filePath.lastIndexOf(".");  
		 String fileType = filePath.substring(lastLength); 
		 // 图片类型  
		 String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1,lastLength);  
		 File zoomFile = new File(savePath +fileName+ "_" + width + "_" + height    + fileType);  
		 try {   
			 ImageIO.write((BufferedImage) image, "jpg", zoomFile);  
		 } catch (Exception e) {   
			 e.printStackTrace();  
		 }  
		 return zoomFile.getPath(); 
	}
	
	/**
	 *  按高的比例更改图片大小 
	 *   @param filePath 源图片路径  
	 *   @param savePath 保存目录  
	 *   @param height  
	 *   @return  
	 *   @throws Exception
	 */ 
	
	public static String getRatioHeight(String filePath,String savePath, int height)   throws Exception {
		File f = new File(filePath);
		BufferedImage bi = ImageIO.read(f);
		double hRatio = (new Integer(height)).doubleValue() / bi.getHeight(); 
		// 高度的比例  
		int width = (int) (hRatio * bi.getWidth()); 
		// 图片转换后的高度  
		Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH); 
		// 设置图像的缩放大小 
		AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(hRatio, hRatio), null); 
		// 设置图像的缩放比例  
		image = op.filter(bi, null);  
		int lastLength = filePath.lastIndexOf(".");
		//  String subFilePath = filePath.substring(0, lastLength); 
		// 得到图片输出路径  
		String fileType = filePath.substring(lastLength); 
		// 图片类型  
		String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1,lastLength);  
		File zoomFile = new File(savePath + fileName +"_" + width + "_" + height + fileType);
		try {
			ImageIO.write((BufferedImage) image, "jpg", zoomFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return zoomFile.getPath();
	} 
	
	/**
	 * 按输入的任意宽高改变图片的大小
	 * @param filePath 源图片路径
	 * @param savePath 保存目录
	 * @param width
	 * @param height
	 * @return
	 * @throws Exception
	 */ 
	
	public static String getFixedIcon(String filePath,String savePath, int width, int height)   throws Exception {
		File f = new File(filePath);
		BufferedImage bi = ImageIO.read(f);
		double wRatio = (new Integer(width)).doubleValue() / bi.getWidth();
		// 宽度的比例 
		double hRatio = (new Integer(height)).doubleValue() / bi.getHeight(); 
		// 高度的比例  
		Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH); 
		// 设置图像的缩放大小 
		AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(wRatio, hRatio), null); 
		// 设置图像的缩放比例  
		image = op.filter(bi, null);
		int lastLength = filePath.lastIndexOf(".");
		String fileType = filePath.substring(lastLength);
		// 图片类型 
		String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1,lastLength);
		File zoomFile = new File(savePath +fileName+ "_" + width + "_" + height+ fileType);
		try {
			ImageIO.write((BufferedImage) image, "jpg", zoomFile);
		} catch (Exception e) {
			e.printStackTrace();
		}  return zoomFile.getPath();
	}
	
	/**
	 * 切割图片
	 * 
	 * @param x 截点横坐标 (从左开始计数)
	 * @param y 截点纵坐标 (从上开始计数)
	 * @param width  截取的宽度
	 * @param height  截取的长度
	 * @param oldpath 图片位置
	 * @param newpath 新生成的图片位置
	 * @author TDW
	 * @date 2018年8月8日
	 */
	public static void cutImage(int x, int y, int width, int height, String oldpath, String newpath) {
		FileInputStream is = null;
		ImageInputStream iis = null;
		// 这个是获取图片扩展名的方法，比如：jpg。我这里有现成的，如果没有，自己实现
		String imgType = StringUtil.getExt(oldpath);
		try {
			is = new FileInputStream(oldpath);
			Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(imgType);
			ImageReader reader = it.next();
			iis = ImageIO.createImageInputStream(is);
			reader.setInput(iis, true);
			ImageReadParam param = reader.getDefaultReadParam();
			Point p = new Point();
			p.setLocation(x, y);
			Dimension d = new Dimension();
			d.setSize(width, height);
			Rectangle rect = new Rectangle(p, d);
			param.setSourceRegion(rect);
			BufferedImage bi = reader.read(0, param);
			ImageIO.write(bi, imgType, new File(newpath));
			is.close();
			iis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @description getImagePixel 获取图片尺寸
	 * @param imgPath
	 * @return
	 * @author TDW
	 * @date 2018年8月8日
	 * @modify_date 
	 * @modify_author
	 * @modify_desc
	 */
	public static Integer[] getImagePixel(String imgPath) {
		Integer[] pixels = new Integer[2];
		BufferedImage sourceImg = null;
		try {
			if(imgPath.indexOf("http")==0 || imgPath.indexOf("www") == 0){
				URL url = new URL(imgPath);
				URLConnection connection = url.openConnection();
				connection.setDoOutput(true);
				sourceImg = ImageIO.read(connection.getInputStream());
			}else{
				sourceImg = ImageIO.read(new FileInputStream(imgPath));
			}
			pixels[0] =sourceImg.getWidth();
			pixels[1] =sourceImg.getHeight();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return pixels;
	}
	
	
	/**
	 * @description downloadPicture, 根据图片url下载图片
	 * @param urlList
	 * @param path
	 * @author TDW
	 * @date 2018年8月8日
	 * @modify_date 
	 * @modify_author
	 * @modify_desc
	 */
	public static void downloadPicture(String urlList, String path) {
		System.out.println("start ....");
		URL url = null;
		DataInputStream dataInputStream = null;
		FileOutputStream fileOutputStream = null;
		ByteArrayOutputStream output = null;
		try {
			url = new URL(urlList);
			dataInputStream = new DataInputStream(url.openStream());
			fileOutputStream = new FileOutputStream(new File(path));
			output = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			fileOutputStream.write(output.toByteArray());
			fileOutputStream.flush();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				dataInputStream.close();
				fileOutputStream.close();
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("end ....");
	}
	
	
}